package com.example.ordersservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.commonutils.R;
import com.example.commonutils.handler.NoqueueException;
import com.example.ordersservice.client.CustomerClient;
import com.example.ordersservice.client.ShoppingCartClient;
import com.example.ordersservice.entity.OrderOrderdetail;
import com.example.ordersservice.entity.OrderOrders;
import com.example.ordersservice.entity.OrderPayLog;
import com.example.ordersservice.mapper.OrderPayLogMapper;
import com.example.ordersservice.service.OrderOrderdetailService;
import com.example.ordersservice.service.OrderOrdersService;
import com.example.ordersservice.service.OrderPayLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.ordersservice.utils.HttpClient;
import com.github.wxpay.sdk.WXPayUtil;
import org.apache.poi.hssf.record.DVALRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2023-07-06
 */
@Service
public class OrderPayLogServiceImpl extends ServiceImpl<OrderPayLogMapper, OrderPayLog> implements OrderPayLogService {

    @Autowired
    private OrderOrdersService ordersService;
    @Autowired
    private OrderOrderdetailService orderdetailService;
    @Autowired
    private ShoppingCartClient shoppingCartClient;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //生成二维码
    @Override
    public Map createNative(String ordersNumber) {
        try{
            //根据订单号查询订单信息
            LambdaQueryWrapper<OrderOrders> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(OrderOrders::getOrdersNumber,ordersNumber);
            OrderOrders order = ordersService.getOne(queryWrapper);
            //使用map设置生成二维码需要的参数
            Map m = new HashMap();
            m.put("appid", "wx74862e0dfcf69954");//应用id
            m.put("mch_id", "1558950191");//商户号
            m.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串
            m.put("body", order.getOrdersDetails());//订单详情
            m.put("out_trade_no", ordersNumber);//订单编号
            m.put("total_fee", order.getOrdersAmount().multiply(new BigDecimal("100")).longValue()+"");//交易金额
            m.put("spbill_create_ip", "127.0.0.1");//终端ip
            m.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n");//回调地址
            m.put("trade_type", "NATIVE");//交易类型
            //通过httpclient发送请求
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();
            //获取返回值
            String xml = client.getContent();
            System.out.println("xml="+xml);
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //封装返回结果集
            Map map = new HashMap<>();
            map.put("out_trade_no", ordersNumber);
            map.put("total_fee", order.getOrdersAmount());
            map.put("result_code", resultMap.get("result_code"));  // 返回二维码操作状态码
            map.put("code_url", resultMap.get("code_url"));  // 二维码地址
            return map;
        }catch (Exception e){
            throw new NoqueueException(20001,"生成二维码失败");
        }
    }

    //查询支付状态
    @Override
    public Map<String, String> queryPayStatus(String ordersNumber) {
        try{
            Map m = new HashMap();
            m.put("appid", "wx74862e0dfcf69954");//应用id
            m.put("mch_id", "1558950191");//商户号
            m.put("out_trade_no", ordersNumber);//订单编号
            m.put("nonce_str", WXPayUtil.generateNonceStr());//随机字符串
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m, "T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();
            String xml = client.getContent();
            System.out.println("订单状态="+xml);
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            throw new NoqueueException(20001,"查询订单状态失败");
        }
    }

    //添加支付记录和更新订单状态
    @Override
    public void updateOrderStatus(Map<String, String> map) {
        //更新订单状态
        //获取订单编号
        String ordersNumber = map.get("out_trade_no");
        //查询订单信息
        LambdaQueryWrapper<OrderOrders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderOrders::getOrdersNumber,ordersNumber);
        OrderOrders order = ordersService.getOne(queryWrapper);
        //更新状态
        if (order.getOrdersStatus().intValue() == 0) return;
        order.setOrdersStatus(0);
        //根据订单编号去查询订单详情表
        LambdaQueryWrapper<OrderOrderdetail> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(OrderOrderdetail::getOrdersNumber,ordersNumber);
        List<OrderOrderdetail> list = orderdetailService.list(queryWrapper1);
        for (int i = 0; i < list.size(); i++) {
            OrderOrderdetail orderdetail = list.get(i);
            String dishId = orderdetail.getDishId();
            Integer dishNumber = orderdetail.getDishNumber();
            //根据dishId和dishNumber减去商品的库存
            R r = shoppingCartClient.subNumber(dishId, dishNumber);
            if (r.getCode()==20001){
                //将订单状态设置为4
                order.setOrdersStatus(4);
            }
        }
        ordersService.updateById(order);
        //TODO 清空缓存
        stringRedisTemplate.delete("cache:ordersAmount");
        //记录日志
        OrderPayLog payLog = new OrderPayLog();
        payLog.setOrderNo(order.getOrdersNumber());//支付订单号
        payLog.setPayTime(new Date());//支付时间
        payLog.setOrdersAmount(order.getOrdersAmount());//总金额(分)
        payLog.setTradeState(map.get("trade_state"));//支付状态
        payLog.setTransactionId(map.get("transaction_id"));//微信订单号
        payLog.setAttr(JSONObject.toJSONString(map));//保存报文到数据库
        baseMapper.insert(payLog);//插入到支付日志表
    }
}
